package com.lambkit.core.config;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.hutool.setting.dialect.Props;
import com.lambkit.core.Lambkit;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yangyong(孤竹行)
 */
public class SettingConfigCenter implements ConfigCenter {

    private Setting setting;
    private String name = "props";

    public SettingConfigCenter(String name) {
        this.name = name;
        if(StrUtil.isBlank(this.name)) {
            this.name = "lambkit";
        }
        setting = readSetting(name + ".txt");
    }

    private Setting readSetting(String propName) {
        Setting theProp = null;
        String rootPath = Lambkit.context().resourceService().getRootPath();
        //优先查找config下有没有properties
        String fileName = rootPath + File.separator + "config" + File.separator + propName;
        File file = new File(fileName);
        if(file.exists()) {
            theProp = new Setting(file, CharsetUtil.CHARSET_UTF_8, true);
        } else {
            //优先查找root下有没有properties
            fileName = rootPath + File.separator + propName;
            if(file.exists()) {
                theProp = new Setting(file, CharsetUtil.CHARSET_UTF_8, true);
            } else {
                theProp = new Setting(propName, CharsetUtil.CHARSET_UTF_8, true);
            }
        }
        if(theProp==null) {
            theProp = new Setting();
        }
        return theProp;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getValue(String key) {
        return setting.getStr(key);
    }

    @Override
    public boolean containsKey(String key) {
        return setting.containsKey(key);
    }

    @Override
    public List<String> getKeys(String prefix) {
        List<String> keyList = new ArrayList<String>();
        for (Map.Entry<String, String> entry : setting.entrySet()) {
            String key = entry.getKey();
            if (key.startsWith(prefix) && entry.getValue() != null) {
                keyList.add(key);
            }
        }
        return keyList;
    }

    @Override
    public boolean refresh() {
        setting.autoLoad(true);
        return true;
    }

    @Override
    public void setValue(String name, String key, String value) {
        if(this.name.equals(name)) {
            setting.set(key, value);
        }
    }

    @Override
    public void removeValue(String key) {
        setting.remove(key);
    }
}
